from django.db.models import Count
from django.http import HttpResponse, JsonResponse, request
from django.shortcuts import render, redirect

from MyDjango import settings
from manage.models import User, Account


# Create your views here.

def index(request):
    is_login = True #True欢迎张三 false显示登录
    users = [
        {"id": 1001, "icon": "nav1.png", "name": "安信工", "age": 20},
        {"id": 1002, "icon": "nav2.png", "name": "莉莉", "age": 20}
    ];
    context = {
        "res" : {"code":200,"msg":"芜湖","cities":[11,22,33]},
        "wea" : {"code":200,"msg":"晴"},
        "is_login":is_login,
        "users":users
    }



    return render(request, 'index.html',context=context,)

def login(request):
    # 如果请求方法是GET，即用户访问登录页面时
    if request.method == "GET":
        # 渲染并返回登录页面的HTML模板
        return render(request, 'login.html')
    # 如果请求方法是POST，即用户提交登录表单时
    elif request.method == "POST":
        # 打印提交的用户名，用于调试或查看
        print(request.POST['username'])
        # 登录验证的逻辑
        # 从数据库中获取用户名对应的账户信息
        account = Account.objects.filter(username=request.POST['username'])
        # 打印账户信息，用于调试
        print(len(account))
        # 检查账户是否存在以及密码是否正确
        if not len(account):
            # 如果账户不存在，返回用户不存在的消息
            return HttpResponse("<script>alert('用户不存在');history.back();</script>")
        if account[0].password != request.POST['password']:
            # 如果密码不正确，返回密码不正确的消息
            return HttpResponse("<script>alert('密码不正确');history.back();</script>")
        # 如果账户存在且密码正确，返回登录成功的消息
        request.session["USERID"] = account[0].id
        return HttpResponse("<script>alert('登录成功');location.href='/user/list/';</script>")

def logout(request):
    request.session.clear()
    return redirect('/login/')

def test(request):
    return render(request, 'test.html')

def user_add(request):
    return render(request, 'useradd.html')

def useredit(request):
    return render(request, 'useredit.html')

#从数据库里取数据
#渲染数据
def user_list(request):
    uid = request.session.get('USERID',None)
    if uid is None:
        return redirect('/login/')

    users = User.objects.all()
    context = {'users':users}
    return render(request, 'userlist.html',context=context)


def user_del(request):
    # 1. 获取请求数据
    id = request.POST['user_id']
    if id is None:
        return JsonResponse({'code': -1, 'msg': "没有找到用户id"})
    # 2. 从数据库取数据并删除
    User.objects.get(id=id).delete()
    # 3. 返回结果
    return JsonResponse({"code": 200, "msg": "删除成功", "data": {"id": id}})


def user_doadd(request):
    # 1. 用户输入数据，点击"提交"按钮
    # 2. 服务端接收用户提交的数据，打印姓名
    print(request.POST['username'])
    # 3. 数据存入数据库
    item = User(
        username=request.POST['username'],
        password="",
        age=request.POST['age'],
        icon=request.POST['icon'],
        category=request.POST['category']
    )
    item.save()
    # 4. 返回存入的结果，类型：JSON，在页面提示执行的结果，成功 OR 失败
    return JsonResponse({'code': 200, "msg": "添加成功", "data": {"id": item.id}})

def user_edit(request):
    # 如果请求方法是GET，即用户访问编辑页面时
    if request.method == "GET":
        # 根据id获取数据，并显示在页面
        id = request.GET['id']
        user = User.objects.get(id=id)
        return render(request, 'useredit.html', context={'user': user})
    # 如果请求方法是POST，即用户提交编辑表单时
    elif request.method == "POST":
        id = request.POST['id']
        user = User.objects.get(id=id)
        user.username = request.POST['username']
        user.age = request.POST['age']
        user.icon = request.POST['icon']
        user.category = request.POST['category']
        res = user.save()  # 保存更新用户信息到数据库
        print(res)  # 打印保存结果
        print(res)
        return JsonResponse({"code": 200, "msg": "更新成功"})  # 返回更新成功的JSON响应
def upload_img(request):
    """上传图片"""
    # 请求方法为POST时，执行文件上传
    if request.method == "GET":
        return render(request, 'upload_img.html')
    elif request.method == "POST":
        # 获取上传的文件，如果没有文件，就默认为None
        my_file = request.FILES.get("icon", None)
        if not my_file:
            return HttpResponse("no files for upload")
        # 打开特定的文件进行二进制的写操作
        with open(f"{settings.MEDIA_ROOT}/{my_file.name}", 'wb+') as f:
            # 分块写入文件;
            for chunk in my_file.chunks():
                f.write(chunk)
            f.close()
        print(my_file.name)
        return JsonResponse({'code': 200, "msg": "添加成功", "data": {"file_name": my_file.name}})
        # return HttpResponse(f"<img src='http://{request.get_host() + settings.MEDIA_URL + my_file.name}' />")


def user_category(request):
    return render(request, template_name='usercategory.html')


def get_category(request):
    # 查询用户类别并统计每个类别的用户数量
    result = User.objects.values('category').annotate(count=Count('category'))
    print(result)

    # 提取类别和数量
    categories = [item['category'] for item in result]
    counts = [item['count'] for item in result]

    # 构建返回的数据结构
    data = {
        'code': 200,
        'msg': '获取用户分类成功',  # 修改了消息内容以反映实际的函数操作
        'data': {
            'categories': categories,
            'counts': counts
        }
    }

    return JsonResponse(data)
